import { PropsWithChildren } from "react";
import { useLaunch, useDidShow, useDidHide } from "@tarojs/taro";
import "./app.scss";
import { setGlobalData, getGlobalData } from "./globalData";
import Taro from "@tarojs/taro";
import "taro-ui/dist/style/index.scss";
import { request } from "@/utils/request";
let appid = getGlobalData("appid");
// 1652973377  已关联微信支付商户号，全称 北京万户良方科技有限公司

function App({ children }: PropsWithChildren<any>) {
  useLaunch(async (options: any) => {
    console.log('options:',options)
    let that = this;
    // console.log('App launched.')
    // console.log('options:', options)
    // 如果存在token和whtoken，则直接登录
    let token = Taro.getStorageSync("token");
    let whToken = Taro.getStorageSync("whToken");
    // 如果token和whtoken同时存在，说明用户是已登录的，不用处理，如果两个有1个不存在，看url上是否存在，url上存在，则存入本地，实现用户免登录
    if (!token || !whToken) {
      // 用户已经登录，不用处理
      let extraData = options.referrerInfo.extraData;
      console.log('extraData:',extraData)
      if (extraData) {
        let paramsToken = extraData.token;
        let paramsWhToken = extraData.whToken;
        let paramsPatientId = extraData.patientId;
        if (paramsToken && paramsWhToken && paramsPatientId) {
          console.log("开始免登录");
          console.log("paramsToken:", paramsToken);
          console.log("paramsWhToken:", paramsWhToken);
          console.log("paramsPatientId:", paramsPatientId);
          Taro.setStorageSync("token", paramsToken);
          Taro.setStorageSync("whToken", paramsWhToken);
          Taro.setStorageSync("patientId", paramsPatientId);
          // 调用wx.login
          // getUser()
          // getPatientInfo()
          Taro.showLoading({
            title: "登录中",
            mask: true,
          });
          await Promise.all([getOpenId(),getUser(), getPatientInfo()]);
          Taro.reLaunch({
            url: "/pages/index/index",
            success: function () {
              Taro.hideLoading();
            },
          });
        }
      }
    }
  });

  function getOpenId() {
    return new Promise((resolve, reject) => {
      Taro.login({
        success: (loginRes) => {
          if (loginRes.code) {
            // 发起网络请求
            request({
              url: "/wechatApp/getOpenId",
              data: {
                code: loginRes.code,
                appid: appid,
              },
              method: "GET",
              success: function (respData) {
                // console.log('getOpenId respData:', respData)
                let openid = respData.openid;
                let unionid = respData.unionid;
                Taro.setStorageSync("openid", openid);
                Taro.setStorageSync("unionid", unionid);
              },
              fail: function (err) {
                Taro.hideLoading();
                Taro.showToast({
                  title: "获取openid失败",
                  icon: "none",
                });
              },
              complete: function () {
                resolve(true);
              },
            });
          }
        },
      });
    });
  }

  function getUser() {
    return new Promise((resolve) => {
      Taro.request({
        url: getGlobalData("url") + "/api/my/show",
        header: { token: Taro.getStorageSync("token") },
        method: "GET",
        success: function (res) {
          if (res.data.respCode == 1) {
            let custBasicInfo = res.data.respData.custBasicInfo;
            console.log("getUser custBasicInfo:", custBasicInfo);
            Taro.setStorageSync("custPhone", custBasicInfo.custPhone);
            Taro.setStorageSync(
              "custHelathClassList",
              res.data.respData.custHelathClassList
            );
            Taro.setStorageSync("goldAllSum", res.data.respData.goldAllSum);
            // Taro.setStorageSync("openid", custBasicInfo.openId);
            Taro.setStorageSync("user", {
              userPhone: custBasicInfo.custPhone,
              id: custBasicInfo.id,
            });
          }
        },
        fail: (res) => {
          console.log("登录失败");
        },
        complete: () => {
          resolve(true);
        },
      });
    });
  }
  function getPatientInfo() {
    return new Promise((resolve, reject) => {
      let patientId = Taro.getStorageSync("patientId");
      let whToken = Taro.getStorageSync("whToken");
      let authHeader = {
        Authorization: `Bearer ${whToken}`,
      };
      if (patientId) {
        Taro.request({
          url: getGlobalData("whUrl") + `/patient/${patientId}`,
          method: "GET",
          header: authHeader,
          success: (res) => {
            if (res.data.code === 0) {
              let data = res.data.data;
              let { realNameAuthenticationPassed } = data;
              Taro.setStorageSync("_patientInfo", data);
              Taro.setStorageSync(
                "hasRealNameAuth",
                realNameAuthenticationPassed
              );
            }
          },
          fail: (err) => {
            console.log("获取getPatientInfo失败", err);
          },
          complete: () => {
            resolve(true);
          },
        });
      } else {
        console.log("getPatientInfo patientId不存在");
        resolve(true);
      }
    });
  }
  function getMiniProgramMenuBarHeight() {
    let systemInfo = Taro.getWindowInfo() as any;
    let menuButtonRect = Taro.getMenuButtonBoundingClientRect();
    let barHeight =
      (menuButtonRect.top - systemInfo.statusBarHeight) * 2 +
      menuButtonRect.height +
      systemInfo.statusBarHeight;
    // console.log('barHeight:',barHeight)
    setGlobalData("navBarHeight", barHeight + "px");
    setGlobalData("menuButtonTop", menuButtonRect.top + "px");
    setGlobalData("menuButtonHeight", menuButtonRect.height + "px");
  }

  useDidShow(() => {
    // console.log('App did show.')
    // 保持屏幕常亮
    Taro.setKeepScreenOn({
      keepScreenOn: true,
    });

    // 设置音频选项
    // Taro.setInnerAudioOption({
    //   mixWithOther: false,
    //   obeyMuteSwitch: false,
    //   success: function (e) {
    //     console.log('setInnerAudioOption play success：',e)
    //   },
    //   fail: function (e) {
    //     // console.log('play fail:',e)
    //   }
    // })
    // 获取屏幕顶部高度
    getMiniProgramMenuBarHeight();
  });
  useDidHide(() => {
    console.log("App did hide.");
  });

  // children 是将要会渲染的页面
  return children;
}

export default App;
